﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace PanasonicWarranty.DAL
{
    public partial class DBSysRole
    {
        public static bool CheckRole(int userId, string link, string roles)
        {
            using (SqlConnection conn = new SqlConnection(Settings.CommonSetting.ConnectionString))
            {
                conn.Open();
                string query = string.Format(@"
                IF EXISTS(
		                SELECT NULL AS [EMPTY]
		                FROM SysGroupRoleMenu grm
			                INNER JOIN SysMenu m on grm.MenuID = m.MenuID
			                INNER JOIN SysRole r ON grm.RoleID = r.RoleID
			                INNER JOIN SysGroup g ON g.GroupID = grm.GroupID
			                INNER JOIN SysUserGroup ug ON ug.GroupID = g.GroupID
		                WHERE m.Link = @Link
			                AND ug.UserID = @UserID
			                {0}
	                ) 
	                SET @RetValue = 1
	                ELSE 
	                SET @RetValue = 0
                ", string.IsNullOrEmpty(roles) ? "" : string.Format("AND r.RoleName IN ({0})", roles));
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.Parameters.Add("@RetValue", SqlDbType.Bit).Direction = ParameterDirection.Output;
                    cmd.Parameters.AddWithValue("@UserID", userId);
                    cmd.Parameters.AddWithValue("@Link", link);
                    cmd.Parameters.AddWithValue("@Role", roles);
                    cmd.ExecuteNonQuery();
                    return (bool)cmd.Parameters["@RetValue"].Value;
                }
            }
        }
    }
}
